package com.whfc.fvs.service.impl;

import com.whfc.common.exception.BizException;
import com.whfc.common.third.uni.UniApi;
import com.whfc.common.third.uni.UniProperties;
import com.whfc.common.third.uni.entity.EventSubscriptionResponse;
import com.whfc.fvs.service.UniEventSubscriptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 宇视事件订阅服务实现类
 */
@Slf4j
@Service
public class UniEventSubscriptionServiceImpl implements UniEventSubscriptionService {

    @Autowired
    private UniApi uniApi;

    @Autowired
    private UniProperties uniProperties;

    /**
     * 订阅宇视事件
     */
    @Override
    public void subscribeEvents() {
        if (!uniProperties.isEventSubscriptionConfigValid()) {
            log.warn("宇视事件订阅配置不完整，跳过订阅");
            return;
        }

        try {
            String eventDest = uniProperties.getEventDest();
            String[] eventTypes = uniProperties.getEventTypesArray();

            uniApi.subscribeEvent(eventDest, eventTypes);
        } catch (BizException e) {
            log.error("宇视事件订阅异常: {}", e.getMessage(), e);
        }
    }

    /**
     * 取消订阅宇视事件
     */
    @Override
    public void unsubscribeEvents() {
        if (!uniProperties.isEventSubscriptionConfigValid()) {
            return;
        }

        try {
            String eventDest = uniProperties.getEventDest();
            String[] eventTypes = uniProperties.getEventTypesArray();

            EventSubscriptionResponse response = uniApi.unsubscribeEvent(eventDest, eventTypes);
            if (response != null && "0".equals(response.getCode())) {
                log.info("宇视事件取消订阅成功");
            } else {
                log.error("宇视事件取消订阅失败: {}", response != null ? response.getMsg() : "未知错误");
            }
        } catch (BizException e) {
            log.error("宇视事件取消订阅异常: {}", e.getMessage(), e);
        }
    }
}